<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|consolas:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Python" />





  <link rel="alternate" href="/atom.xml" title="🐕 @Leeifme" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="Python虚拟环境的搭建和配置 Python易用，但用好却不易，其中比较头疼的就是包管理和Python不同版本的问题，特别是当你使用Windows的时候。为了解决这些问题，有不少发行版的Python，比如WinPython、Anaconda等，这些发行版将python和许多常用的package打包，方便pythoners直接使用，此外，还有virtualenv、pyenv等工具管理虚拟环境。 这">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="Python虚拟坏境的搭建和配置">
<meta property="og:url" content="http://www.leeif.me/coding/python/Python虚拟坏境的搭建和配置/index.html">
<meta property="og:site_name" content="🐕 @Leeifme">
<meta property="og:description" content="Python虚拟环境的搭建和配置 Python易用，但用好却不易，其中比较头疼的就是包管理和Python不同版本的问题，特别是当你使用Windows的时候。为了解决这些问题，有不少发行版的Python，比如WinPython、Anaconda等，这些发行版将python和许多常用的package打包，方便pythoners直接使用，此外，还有virtualenv、pyenv等工具管理虚拟环境。 这">
<meta property="og:updated_time" content="2017-07-14T09:21:04.106Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python虚拟坏境的搭建和配置">
<meta name="twitter:description" content="Python虚拟环境的搭建和配置 Python易用，但用好却不易，其中比较头疼的就是包管理和Python不同版本的问题，特别是当你使用Windows的时候。为了解决这些问题，有不少发行版的Python，比如WinPython、Anaconda等，这些发行版将python和许多常用的package打包，方便pythoners直接使用，此外，还有virtualenv、pyenv等工具管理虚拟环境。 这">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: undefined,
      author: 'Author'
    }
  };
</script>




  <link rel="canonical" href="http://www.leeif.me/coding/python/Python虚拟坏境的搭建和配置/"/>

  <title> Python虚拟坏境的搭建和配置 | 🐕 @Leeifme </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>
    
    <header id="header_post" class="header" itemscope itemtype="http://schema.org/WPHeader" style="background-image: url('http://orj2jcr7i.bkt.clouddn.com/python%20homepage.png');">
      <div class="header-inner-post"><a class="site-home" href="/">🐕 @Leeifme</a>

<div class="site-meta custom-logo">
  
  
  
    <div class="site-meta-headline">
      <a>
        <img class="custom-logo-image" src="/images/logo.png" style="width: 80px"
             alt="🐕 @Leeifme"/>
      </a>
    </div>
  

  
  
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        
        
           <li class="menu-item menu-item-about">
             <a href="/about" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
               
               
               about
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-movie">
             <a href="/movie" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-superscript"></i> <br />
               
               
               movie
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-coding">
             <a href="/categories/coding" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-cogs"></i> <br />
               
               
               coding
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-archives">
             <a href="/archives" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
               
               
               archives
             </a>
           </li>
        
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <input type="text" id="local-search-input">
 <span class="search-icon fa fa-search"></span>
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
      <div class="header-post"> 
  <div class="post-header">
      <div class="tags">
      
        <a href="/tags/Python/" rel="tag" title="Python">Python</a>
      
      </div>
      <h1>Python虚拟坏境的搭建和配置</h1>
      <h2 class="subtitle"></h2>
      <div class="post-time">
        <span class="post-meta-item-text">Posted on </span>
        <time itemprop="dateCreated" datetime="2017-07-14T17:12:00+08:00" content="2017-07-14" title="2017-07-14 17:12:00">
          2017-07-14
        </time>
      </div>
  </div>
 </div>
    </header>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Python虚拟坏境的搭建和配置
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2017-07-14T17:12:00+08:00" content="2017-07-14">
              2017-07-14
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/coding/" itemprop="url" rel="index">
                    <span itemprop="name">coding</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/coding/python/" itemprop="url" rel="index">
                    <span itemprop="name">python</span>
                  </a>
                </span>

                
                

              
            </span>
          

          <!-- 
            
           -->

          

          
          
             <span id="/coding/python/Python虚拟坏境的搭建和配置/" class="leancloud_visitors" data-flag-title="Python虚拟坏境的搭建和配置">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv"><i class="fa fa-eye"> </i>
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <link rel="stylesheet" type="text/css" href="/assets/css/DPlayer.min.css"><script src="/assets/js/DPlayer.min.js"> </script><script src="/assets/js/APlayer.min.js"> </script><h2 id="Python虚拟环境的搭建和配置"><a href="#Python虚拟环境的搭建和配置" class="headerlink" title="Python虚拟环境的搭建和配置"></a>Python虚拟环境的搭建和配置</h2><blockquote>
<p>Python易用，但用好却不易，其中比较头疼的就是包管理和Python不同版本的问题，特别是当你使用Windows的时候。为了解决这些问题，有不少发行版的Python，比如WinPython、Anaconda等，这些发行版将python和许多常用的package打包，方便pythoners直接使用，此外，还有virtualenv、pyenv等工具管理虚拟环境。</p>
<p>这篇文章主要就是记录了不使用发行版，和最终使用发行版Anaconda，因为其强大而方便的包管理与环境管理的功能。</p>
</blockquote>
<p><strong>系统环境：</strong></p>
<ul>
<li>Win10</li>
<li>Python 3.6.0</li>
<li>Anaconda3</li>
</ul>
<h2 id="不使用发行版"><a href="#不使用发行版" class="headerlink" title="不使用发行版"></a>不使用发行版</h2><p><strong>借助<code>virtualenvwrapper</code>工具实现虚拟环境</strong></p>
<p>首先，安装：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="attribute">pip</span> install virtualenvwrapper</div></pre></td></tr></table></figure>
<p><strong>注：</strong> 可以使用豆瓣源<code>https://pypi.douban.com/simple/</code></p>
<p>但是不幸的是，在我的系统上报错了</p>
<a id="more"></a>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div></pre></td><td class="code"><pre><div class="line"><span class="attribute">Collecting</span> virtualenvwrapper</div><div class="line">  Using cached virtualenvwrapper-<span class="number">4</span>.<span class="number">7</span>.<span class="number">2</span>.tar.gz</div><div class="line">    Complete output from command python setup.py egg_info:</div><div class="line">    Traceback (most recent call <span class="literal">last</span>):</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\urllib\request.py"</span>, line <span class="number">1318</span>, in do_open</div><div class="line">        encode_chunked=req.has_header(<span class="string">'Transfer-encoding'</span>))</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\http\client.py"</span>, line <span class="number">1239</span>, in request</div><div class="line">        self._send_request(method, url, body, headers, encode_chunked)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\http\client.py"</span>, line <span class="number">1285</span>, in _send_request</div><div class="line">        self.endheaders(body, encode_chunked=encode_chunked)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\http\client.py"</span>, line <span class="number">1234</span>, in endheaders</div><div class="line">        self._send_output(message_body, encode_chunked=encode_chunked)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\http\client.py"</span>, line <span class="number">1026</span>, in _send_output</div><div class="line">        self.send(msg)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\http\client.py"</span>, line <span class="number">964</span>, in send</div><div class="line">        self.connect()</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\http\client.py"</span>, line <span class="number">1400</span>, in connect</div><div class="line">        server_hostname=server_hostname)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\ssl.py"</span>, line <span class="number">401</span>, in wrap_socket</div><div class="line">        _context=self, _session=session)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\ssl.py"</span>, line <span class="number">808</span>, in __init__</div><div class="line">        self.do_handshake()</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\ssl.py"</span>, line <span class="number">1061</span>, in do_handshake</div><div class="line">        self._sslobj.do_handshake()</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\ssl.py"</span>, line <span class="number">683</span>, in do_handshake</div><div class="line">        self._sslobj.do_handshake()</div><div class="line">    socket.timeout: _ssl.c:<span class="number">733</span>: The handshake operation timed out</div><div class="line"></div><div class="line">    During handling of the above exception, another exception occurred:</div><div class="line"></div><div class="line">    Traceback (most recent call <span class="literal">last</span>):</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">746</span>, in open_url</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">947</span>, in _socket_timeout</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">1065</span>, in open_with_auth</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\urllib\request.py"</span>, line <span class="number">223</span>, in urlopen</div><div class="line">        return opener.open(url, data, timeout)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\urllib\request.py"</span>, line <span class="number">526</span>, in open</div><div class="line">        response = self._open(req, data)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\urllib\request.py"</span>, line <span class="number">544</span>, in _open</div><div class="line">        <span class="string">'_open'</span>, req)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\urllib\request.py"</span>, line <span class="number">504</span>, in _call_chain</div><div class="line">        result = func(*args)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\urllib\request.py"</span>, line <span class="number">1361</span>, in https_open</div><div class="line">        context=self._context, check_hostname=self._check_hostname)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\urllib\request.py"</span>, line <span class="number">1320</span>, in do_open</div><div class="line">        raise URLError(err)</div><div class="line">    urllib.<span class="literal">error</span>.URLError: &lt;urlopen <span class="literal">error</span> _ssl.c:<span class="number">733</span>: The handshake operation timed out&gt;</div><div class="line"></div><div class="line">    During handling of the above exception, another exception occurred:</div><div class="line"></div><div class="line">    Traceback (most recent call <span class="literal">last</span>):</div><div class="line">      File <span class="string">"&lt;string&gt;"</span>, line <span class="number">1</span>, in &lt;module&gt;</div><div class="line">      File <span class="string">"C:\Users\leeif\AppData\Local\Temp\pip-build-somfu2_x\virtualenvwrapper\setup.py"</span>, line <span class="number">7</span>, in &lt;module&gt;</div><div class="line">        pbr=True,</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\distutils\core.py"</span>, line <span class="number">108</span>, in setup</div><div class="line">        _setup_distribution = dist = klass(attrs)</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\dist.py"</span>, line <span class="number">315</span>, in __init__</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\dist.py"</span>, line <span class="number">361</span>, in fetch_build_eggs</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\pkg_resources\__init__.py"</span>, line <span class="number">851</span>, in resolve</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\pkg_resources\__init__.py"</span>, line <span class="number">1123</span>, in best_match</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\pkg_resources\__init__.py"</span>, line <span class="number">1135</span>, in obtain</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\dist.py"</span>, line <span class="number">428</span>, in fetch_build_egg</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\command\easy_install.py"</span>, line <span class="number">652</span>, in easy_install</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">635</span>, in fetch_distribution</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">616</span>, in find</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">559</span>, in download</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">804</span>, in _download_url</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">810</span>, in _attempt_download</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">709</span>, in _download_to</div><div class="line">      File <span class="string">"D:\python\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\package_index.py"</span>, line <span class="number">760</span>, in open_url</div><div class="line">    distutils.errors.DistutilsError: Download <span class="literal">error</span> for https://pypi.python.org/packages/d5/d6/f2bf137d71e4f213b575faa9eb426a8775732432edb67588a8ee836ecb80/pbr-3.1.1.tar.gz#md5=4e82c2e07af544c56a5b71c801525b00: _ssl.c:<span class="number">733</span>: The handshake operation timed out</div><div class="line"></div><div class="line">    ----------------------------------------</div><div class="line">Command <span class="string">"python setup.py egg_info"</span> failed with <span class="literal">error</span> code <span class="number">1</span> in .....\Local\Temp\pip-build-somfu2_x\virtualenvwrapper\</div></pre></td></tr></table></figure>
<p><strong>解决办法：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">pip install -i https://pypi.douban.com/simple/ pbr</div><div class="line"></div><div class="line">pip install -i https://pypi.douban.com/simple/ stevedore</div><div class="line"></div><div class="line">pip install -i https://pypi.douban.com/simple/ virtualenvwrapper</div></pre></td></tr></table></figure>
<p>然后使用<code>mkvirutualenv --python=(python&#39;s path) name</code>新建虚拟坏境</p>
<h2 id="使用Anaconda发行版"><a href="#使用Anaconda发行版" class="headerlink" title="使用Anaconda发行版"></a>使用Anaconda发行版</h2><blockquote>
<p><a href="https://www.continuum.io/why-anaconda" target="_blank" rel="external">Anaconda</a> 是一个用于科学计算的 Python 发行版，支持 Linux, Mac, Windows 系统，提供了包管理与环境管理的功能，可以很方便地解决多版本 python 并存、切换以及各种第三方包安装问题。Anaconda 利用工具 / 命令<code>conda</code>来进行 package 和 environment 的管理，并且已经包含了 Python 和相关的配套工具。</p>
<p><code>conda</code>可以理解为一个工具，也是一个可执行命令，其核心功能是<strong>包管理</strong>与<strong>环境管理</strong>。包管理与 pip 的使用类似，环境管理则允许用户方便地安装不同版本的 python 并可以快速切换。Anaconda 则是一个打包的集合，里面预装好了 conda、某个版本的 python、众多 packages、科学计算工具等等，所以也称为 Python 的一种发行版。</p>
</blockquote>
<h2 id="Anaconda-的安装"><a href="#Anaconda-的安装" class="headerlink" title="Anaconda 的安装"></a>Anaconda 的安装</h2><p>Anaconda 的下载页参见<a href="https://www.continuum.io/downloads" target="_blank" rel="external">官网下载</a>，Linux、Mac、Windows 均支持。</p>
<p>安装时，会发现有两个不同版本的 Anaconda，分别对应 Python 2.7 和 Python 3.5，两个版本其实除了这点区别外其他都一样。后面我们会看到，安装哪个版本并不本质，因为通过环境管理，我们可以很方便地切换运行时的 Python 版本。（由于我常用的 Python 是 2.7 和 3.4，因此倾向于直接安装 Python 2.7 对应的 Anaconda）</p>
<p>下载后直接按照说明安装即可。这里想提醒一点：尽量按照 Anaconda 默认的行为安装——不使用 root 权限，仅为个人安装，安装目录设置在个人主目录下（Windows 就无所谓了）。这样的好处是，同一台机器上的不同用户完全可以安装、配置自己的 Anaconda，不会互相影响。</p>
<p>对于 Mac、Linux 系统，Anaconda 安装好后，实际上就是在主目录下多了个文件夹（<code>~/anaconda</code>）而已，Windows 会写入注册表。安装时，安装程序会把 bin 目录加入 PATH（Linux/Mac 写入<code>~/.bashrc</code>，Windows 添加到系统变量 PATH），这些操作也完全可以自己完成。以 Linux/Mac 为例，安装完成后设置 PATH 的操作是</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"># 将 anaconda 的 bin 目录加入 PATH，根据版本不同，也可能是~/anaconda3/bin</div><div class="line">echo &apos;export PATH=&quot;~/anaconda2/bin:$PATH&quot;&apos; &gt;&gt; ~/.bashrc</div><div class="line"># 更新 bashrc 以立即生效</div><div class="line">source ~/.bashrc</div></pre></td></tr></table></figure>
<p>配置好 PATH 后，可以通过<code>which conda</code>或<code>conda --version</code>命令检查是否正确。假如安装的是 Python 2.7 对应的版本，运行<code>python --version</code>或<code>python -V</code>可以得到 Python 2.7.12 :: Anaconda 4.1.1 (64-bit)，也说明该发行版默认的环境是 Python 2.7。</p>
<h2 id="Conda-的环境管理"><a href="#Conda-的环境管理" class="headerlink" title="Conda 的环境管理"></a>Conda 的环境管理</h2><p>Conda 的环境管理功能允许我们同时安装若干不同版本的 Python，并能自由切换。对于上述安装过程，假设我们采用的是 Python 2.7 对应的安装包，那么 Python 2.7 就是默认的环境（默认名字是<code>root</code>，注意这个 root 不是超级管理员的意思）。</p>
<p>假设我们需要安装 Python 3.4，此时，我们需要做的操作如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"># 创建一个名为 python34 的环境，指定 Python 版本是 3.4（不用管是 3.4.x，conda 会为我们自动寻找 3.4.x 中的最新版本）</div><div class="line">conda create --name python34 python=3.4</div><div class="line"> </div><div class="line"># 安装好后，使用 activate 激活某个环境</div><div class="line">activate python34 # for Windows</div><div class="line">source activate python34 # for Linux &amp; Mac</div><div class="line"># 激活后，会发现 terminal 输入的地方多了 python34 的字样，实际上，此时系统做的事情就是把默认 2.7 环境从 PATH 中去除，再把 3.4 对应的命令加入 PATH</div><div class="line"> </div><div class="line"># 此时，再次输入</div><div class="line">python --version</div><div class="line"># 可以得到 `Python 3.4.5 :: Anaconda 4.1.1 (64-bit)`，即系统已经切换到了 3.4 的环境</div><div class="line"> </div><div class="line"># 如果想返回默认的 python 2.7 环境，运行</div><div class="line">deactivate python34 # for Windows</div><div class="line">source deactivate python34 # for Linux &amp; Mac</div><div class="line"> </div><div class="line"># 删除一个已有的环境</div><div class="line">conda remove --name python34 --all</div></pre></td></tr></table></figure>
<p>用户安装的不同 python 环境都会被放在目录<code>~/anaconda/envs</code>下，可以在命令中运行<code>conda info -e</code>查看已安装的环境，当前被激活的环境会显示有一个星号或者括号。</p>
<p>说明：有些用户可能经常使用 python 3.4 环境，因此直接把<code>~/anaconda/envs/python34</code>下面的 bin 或者 Scripts 加入 PATH，去除 anaconda 对应的那个 bin 目录。这个办法，怎么说呢，也是可以的，但总觉得不是那么 elegant……</p>
<p>如果直接按上面说的这么改 PATH，你会发现 conda 命令又找不到了（当然找不到啦，因为 conda 在<code>~/anaconda/bin</code>里呢），这时候怎么办呢？方法有二：1. 显式地给出 conda 的绝对地址 2. 在 python34 环境中也安装 conda 工具（推荐）。</p>
<h2 id="Conda-的包管理"><a href="#Conda-的包管理" class="headerlink" title="Conda 的包管理"></a>Conda 的包管理</h2><p>Conda 的包管理就比较好理解了，这部分功能与<code>pip</code>类似。</p>
<p>例如，如果需要安装 scipy：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"># 安装 scipy</div><div class="line">conda install scipy</div><div class="line"># conda 会从从远程搜索 scipy 的相关信息和依赖项目，对于 python 3.4，conda 会同时安装 numpy 和 mkl（运算加速的库）</div><div class="line"> </div><div class="line"># 查看已经安装的 packages</div><div class="line">conda list</div><div class="line"># 最新版的 conda 是从 site-packages 文件夹中搜索已经安装的包，不依赖于 pip，因此可以显示出通过各种方式安装的包</div></pre></td></tr></table></figure>
<p>conda 的一些常用操作如下：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="attribute">conda</span> list</div><div class="line"> </div><div class="line"><span class="comment"># 查看某个指定环境的已安装包</span></div><div class="line">conda list -n python34</div><div class="line"> </div><div class="line"><span class="comment"># 查找 package 信息</span></div><div class="line">conda search numpy</div><div class="line"> </div><div class="line"><span class="comment"># 安装 package</span></div><div class="line">conda install -n python34 numpy</div><div class="line"><span class="comment"># 如果不用 - n 指定环境名称，则被安装在当前活跃环境</span></div><div class="line"><span class="comment"># 也可以通过 - c 指定通过某个 channel 安装</span></div><div class="line"> </div><div class="line"><span class="comment"># 更新 package</span></div><div class="line">conda update -n python34 numpy</div><div class="line"> </div><div class="line"><span class="comment"># 删除 package</span></div><div class="line">conda remove -n python34 numpy</div></pre></td></tr></table></figure>
<p>前面已经提到，conda 将 conda、python 等都视为 package，因此，完全可以使用 conda 来管理 conda 和 python 的版本，例如</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># 更新 conda，保持 conda 最新</span></div><div class="line">conda update conda</div><div class="line"> </div><div class="line"><span class="comment"># 更新 anaconda</span></div><div class="line">conda update anaconda</div><div class="line"> </div><div class="line"><span class="comment"># 更新 python</span></div><div class="line">conda update python</div><div class="line"><span class="comment"># 假设当前环境是 python 3.4, conda 会将 python 升级为 3.4.x 系列的当前最新版本</span></div></pre></td></tr></table></figure>
<p>补充：如果创建新的 python 环境，比如 3.4，运行<code>conda create -n python34 python=3.4</code>之后，conda 仅安装 python 3.4 相关的必须项，如 python, pip 等，如果希望该环境像默认环境那样，安装 anaconda 集合包，只需要：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># 在当前环境下安装 anaconda 包集合</span></div><div class="line">conda install anaconda</div><div class="line"> </div><div class="line"><span class="comment"># 结合创建环境的命令，以上操作可以合并为</span></div><div class="line">conda create -n python34 python=<span class="number">3.4</span> anaconda</div><div class="line"><span class="comment"># 也可以不用全部安装，根据需求安装自己需要的 package 即可</span></div></pre></td></tr></table></figure>
<h2 id="设置国内镜像"><a href="#设置国内镜像" class="headerlink" title="设置国内镜像"></a>设置国内镜像</h2><p>如果需要安装很多 packages，你会发现 conda 下载的速度经常很慢，因为 Anaconda.org 的服务器在国外。所幸的是，清华 TUNA 镜像源有 Anaconda 仓库的镜像，我们将其加入 conda 的配置即可：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># 添加 Anaconda 的 TUNA 镜像</span></div><div class="line">conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/</div><div class="line"><span class="comment"># TUNA 的 help 中镜像地址加有引号，需要去掉</span></div><div class="line"> </div><div class="line"><span class="comment"># 设置搜索时显示通道地址</span></div><div class="line">conda config --set show_channel_urls yes</div></pre></td></tr></table></figure>
<p>执行完上述命令后，会生成<code>~/.condarc</code>(Linux/Mac) 或<code>C:UsersUSER_NAME.condarc</code>文件，记录着我们对 conda 的配置，直接手动创建、编辑该文件是相同的效果。</p>
<p><strong>ok,配置完成，Just Try！</strong></p>

      
    </div>


    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag">#Python</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/technology/other/如何制作一份优雅的简历/" rel="next" title="LaTeX+ Sublime 制作一份优雅的简历">
                <i class="fa fa-chevron-left"></i> LaTeX+ Sublime 制作一份优雅的简历
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/technology/collect/常见面试题整理——操作系统/" rel="prev" title="常见面试题整理——操作系统">
                常见面试题整理——操作系统 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
      
        
          <ul class="sidebar-nav motion-element">
            <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
              Table of Contents
            </li>
            <li class="sidebar-nav-overview" data-target="site-overview">
              Overview
            </li>
          </ul>
        
      



      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="睡沙发的沙皮狗" />
          <p class="site-author-name" itemprop="name">睡沙发的沙皮狗</p>
           
              <p class="site-description motion-element" itemprop="description">睡沙发的沙皮狗 Leeifme</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">17</span>
                <span class="site-state-item-name">posts</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">categories</span>
              
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">tags</span>
              
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/leeifme" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/5406937103/profile?topnav=1&wvr=6" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        

        


      </section>
      
        
        <!--noindex-->
          <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
            <div class="post-toc">

              
                
              

              
                <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Python虚拟环境的搭建和配置"><span class="nav-number">1.</span> <span class="nav-text">Python虚拟环境的搭建和配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#不使用发行版"><span class="nav-number">2.</span> <span class="nav-text">不使用发行版</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Anaconda发行版"><span class="nav-number">3.</span> <span class="nav-text">使用Anaconda发行版</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Anaconda-的安装"><span class="nav-number">4.</span> <span class="nav-text">Anaconda 的安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Conda-的环境管理"><span class="nav-number">5.</span> <span class="nav-text">Conda 的环境管理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Conda-的包管理"><span class="nav-number">6.</span> <span class="nav-text">Conda 的包管理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置国内镜像"><span class="nav-number">7.</span> <span class="nav-text">设置国内镜像</span></a></li></ol></div>
              

            </div>
          </section>
        <!--/noindex-->
        
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">睡沙发的沙皮狗</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/zproo/hexo-blog">
    Next
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span></span>
  

  
    <span class="site-pv"><i class="fa fa-eye"> </i><span class="busuanzi-value" id="busuanzi_value_site_pv"></span></span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  





	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 92841, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 92841, xid: "coding/python/Python虚拟坏境的搭建和配置/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/92841/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	







  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').fadeToggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ decodeURIComponent(data_url) +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').fadeOut(function() {
          $(".popoverlay").remove();
          $('body').css('overflow', '');
      });
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("6mFxqINb4RcjTGhNbtCzfWI1-gzGzoHsz", "c4qK91bIu9qFdGeimnKdriiK");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


</body>
</html>
